package com.ubb.damate.service.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import com.ubb.damate.model.User;
import com.ubb.damate.service.UserServiceLocal;
import com.ubb.damate.service.UserServiceRemote;

/** Session Bean implementation class UserService */
@Stateless
public class UserService implements UserServiceRemote, UserServiceLocal {

	@PersistenceContext(unitName = "damate-pu")
	private EntityManager	em;

	@Override
	public User createOrUpdate(User user) {
		return em.merge(user);
	}

	@Override
	public void delete(User user) {
		em.remove(em.merge(user));
	}

	@Override
	public User find(User user) {
		return em.find(com.ubb.damate.model.User.class, user.getUsername());
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<User> allUser() {
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
		Query query = em.createQuery(criteriaQuery);

		return query.getResultList();
	}

	@Override
	public boolean login(String username, String password) {
		User user = new User();
		user.setUsername(username);
		user = find(user);
		if (user.getPassword().equals(password)) {
			return true;
		}
		return false;
	}

}